/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EnderecoDialog.java
 *
 * Created on Jun 8, 2011, 11:11:52 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleEndereco;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.Endereco;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class EnderecoDialog extends javax.swing.JDialog {

    private int codigoCidade;
    private int codigoBairro;
    private Endereco endereco;

    public EnderecoDialog(java.awt.Frame parent, String title, boolean modal, String cep) {
        super(parent, title, modal);
        initComponents();
        setLocationRelativeTo(null);
        cepTextField.setText(cep);
        buscaCep();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel7 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        logradouroTextField = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        cepTextField = new javax.swing.JFormattedTextField();
        estadoTextField = new javax.swing.JFormattedTextField();
        bairroTextField = new javax.swing.JTextField();
        cidadeTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        addBairroButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();
        salvarButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Endereço", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel6.setText("Código postal (CEP):");

        jLabel8.setText("Logradouro:");

        jLabel9.setText("Estado:");

        jLabel10.setText("Cidade:");

        jLabel11.setText("Bairro:");

        try {
            cepTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cepTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        cepTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cepTextFieldActionPerformed(evt);
            }
        });

        estadoTextField.setEditable(false);
        estadoTextField.setFocusable(false);

        bairroTextField.setEditable(false);

        cidadeTextField.setEditable(false);
        cidadeTextField.setFocusable(false);

        jLabel1.setForeground(new java.awt.Color(51, 51, 255));
        jLabel1.setText("O bairro não é esse?");

        addBairroButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/add16x16.png"))); // NOI18N
        addBairroButton.setText("Cadastrar novo bairro");
        addBairroButton.setToolTipText("Cadastrar novo bairro");
        addBairroButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addBairroButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addComponent(cepTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(471, 471, 471))
                            .addComponent(logradouroTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 637, Short.MAX_VALUE)))
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGap(72, 72, 72)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel11)
                            .addComponent(jLabel10)
                            .addComponent(jLabel9))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel7Layout.createSequentialGroup()
                                .addComponent(bairroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(addBairroButton, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE))
                            .addComponent(estadoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cepTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(logradouroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bairroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(jLabel1)
                    .addComponent(addBairroButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(estadoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });

        salvarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/add16x16.png"))); // NOI18N
        salvarButton.setText("Cadastrar");
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(561, Short.MAX_VALUE)
                .addComponent(salvarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fecharButton)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fecharButton)
                    .addComponent(salvarButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cepTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cepTextFieldActionPerformed
        buscaCep();
}//GEN-LAST:event_cepTextFieldActionPerformed

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        if ("     -   ".equals(cepTextField.getText())) {
            JOptionPane.showMessageDialog(null, "O cep não foi informado corretamente.", "Informação", JOptionPane.WARNING_MESSAGE);
            cepTextField.requestFocus();
            return;
        }
        if (logradouroTextField.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "O logradouro não foi informado.", "Informação", JOptionPane.WARNING_MESSAGE);
            logradouroTextField.requestFocus();
            return;
        }
        if (bairroTextField.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "O bairro não foi informado.", "Informação", JOptionPane.WARNING_MESSAGE);
            bairroTextField.requestFocus();
            return;
        }
        String cep = cepTextField.getText().replace("-", "");
        String logradouro = logradouroTextField.getText();
        ControleEndereco controle = new ControleEndereco();
        endereco = new Endereco();
        endereco.setCodigoBairro(codigoBairro);
        endereco.setCodigoCidade(codigoCidade);
        endereco.setCep(cep);
        endereco.setLougradouro(logradouro);
        try {
            controle.cadastrar(endereco);
            JOptionPane.showMessageDialog(null, "O endereço foi cadastrado com sucesso",
                    "Informação", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }//GEN-LAST:event_salvarButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        dispose();
    }//GEN-LAST:event_fecharButtonActionPerformed

    private void addBairroButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBairroButtonActionPerformed
        String bairroStr = JOptionPane.showInputDialog(this, "Informe o nome do bairro:", "Cadastrar bairro", JOptionPane.QUESTION_MESSAGE);
        if (bairroStr != null && bairroStr.length() > 0) {
            try {
                ControleEndereco controle = new ControleEndereco();
                this.codigoBairro = controle.cadastrarBairro(bairroStr, codigoCidade);
                JOptionPane.showMessageDialog(null, "O bairro foi cadastrado com sucesso.",
                        "Informação", JOptionPane.INFORMATION_MESSAGE);
                bairroTextField.setText(bairroStr);
            } catch (PersistenciaException pex) {
                System.out.println(pex.getMessage());
            }
        }
    }//GEN-LAST:event_addBairroButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                EnderecoDialog dialog = new EnderecoDialog(new javax.swing.JFrame(),
                        "TBP - Endereço", true, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addBairroButton;
    private javax.swing.JTextField bairroTextField;
    private javax.swing.JFormattedTextField cepTextField;
    private javax.swing.JTextField cidadeTextField;
    private javax.swing.JFormattedTextField estadoTextField;
    private javax.swing.JButton fecharButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JTextField logradouroTextField;
    private javax.swing.JButton salvarButton;
    // End of variables declaration//GEN-END:variables

    private void buscaCep() {
        String cep = cepTextField.getText().replace("-", "");
        ControleEndereco controle = new ControleEndereco();
        try {
            List<Endereco> enderecoList = controle.pesquisar(cep);
            if(enderecoList.isEmpty()) {
                addBairroButton.setEnabled(false);
                salvarButton.setEnabled(false);
            } else {
                mostraEndereco(controle.pesquisar(cep).get(0));
            }
        } catch (PersistenciaException pe) {
            System.out.println(pe.getMessage());
        }
    }

    public void mostraEndereco(Endereco e) {
        if (e != null) {
            this.codigoBairro = e.getCodigoBairro();
            this.codigoCidade = e.getCodigoCidade();
            cepTextField.setText(e.getCep());
            logradouroTextField.setText(e.getLougradouro());
            bairroTextField.setText(e.getBairro());
            cidadeTextField.setText(e.getCidade());
            estadoTextField.setText(e.getEstado());
            logradouroTextField.requestFocus();
            logradouroTextField.selectAll();
        } else {
            limpaEndereco();
        }
    }

    private void limpaEndereco() {
        cepTextField.setText(null);
        bairroTextField.setText(null);
        cidadeTextField.setText(null);
        estadoTextField.setText(null);
        logradouroTextField.setText(null);
    }

    public Endereco getEndereco() {
        return endereco;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
